package com.onlineMIS.ORM.DAO.headQ.user;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;


import com.onlineMIS.ORM.DAO.BaseDAO;
import com.onlineMIS.ORM.DAO.BaseDAOMS;
import com.onlineMIS.ORM.entity.chainS.user.ChainRoleType;
import com.onlineMIS.ORM.entity.headQ.HR.MagerEmployeeRelationship;
import com.onlineMIS.ORM.entity.headQ.user.RoleFunctionality;
import com.onlineMIS.ORM.entity.headQ.user.UserFunctionalityDeleted;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.loggerLocal;
import com.opensymphony.xwork2.inject.util.FinalizablePhantomReference;

@Repository
public class UserInforDaoImpl extends BaseDAO<UserInfor>{
	
	


	public void initialize(UserInfor userInfor) {
		this.getHibernateTemplate().initialize(userInfor.getEmployeeUnder_Set());
		//this.getHibernateTemplate().initialize(userInfor.getUserFunction_Set());
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Configuration configuration = new Configuration().configure();
		
		SessionFactory sFactory = configuration.buildSessionFactory();
		
		Session session = sFactory.openSession();
		
		Transaction transaction = session.beginTransaction();
		
		UserInfor userInfor = (UserInfor)session.get(UserInfor.class, 1);

//		Iterator<UserFunctionality> functions= userInfor.getUserFunction_Set().iterator();
//		
//		System.out.println(functions.hasNext());
		
		transaction.commit();
		
		session.close();
	}



	public void deleteFunctionByUserID(final int user_id) {
		this.getHibernateTemplate().setCacheQueries(true);
		final String hql = "delete from UserFunctionality u where u.user_id = ?";
		
		try{
			this.getHibernateTemplate().execute(new HibernateCallback<Integer>(){
	            public Integer doInHibernate(Session session) throws HibernateException,SQLException{
	        		
	        		Query q= session.createQuery(hql);
	        		
	        		q.setParameter(0, user_id);
	        		
	    			int success = q.executeUpdate();
	    			return success;
	           }
	     });
		} catch (Exception e) {
			loggerLocal.error(e);
		}
	}
	
	public void deleteFunctionByRoleID(final int role_id) {
		this.getHibernateTemplate().setCacheQueries(true);
		final String hql = "delete from RoleFunctionality u where u.role_id = ?";
		
		try{
			this.getHibernateTemplate().execute(new HibernateCallback<Integer>(){
	            public Integer doInHibernate(Session session) throws HibernateException,SQLException{
	        		
	        		Query q= session.createQuery(hql);
	        		
	        		q.setParameter(0, role_id);
	        		
	    			int success = q.executeUpdate();
	    			return success;
	           }
	     });
		} catch (Exception e) {
			loggerLocal.error(e);
		}
	}

	public void addFunctions(List<UserFunctionalityDeleted> userFunctionalities) {
		this.getHibernateTemplate().setCacheQueries(true);
		for (int i =0; i < userFunctionalities.size(); i++){
			UserFunctionalityDeleted functionality = userFunctionalities.get(i);
			this.getHibernateTemplate().save(functionality);
		}
		
	}

	public List<UserInfor> getAllNormalUsers() {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		criteria.add(Restrictions.ne("user_name", "admin"));
		criteria.add(Restrictions.ne("department", UserInfor.SALES_CODE));
		criteria.add(Restrictions.ne("department", UserInfor.LOGISTIC_CODE));
		criteria.add(Restrictions.eq("resign", UserInfor.NORMAL_ACCOUNT));
		criteria.addOrder(Order.asc("pinyin"));
		
		List<UserInfor> user_list = this.getByCritera(criteria, true);
		
		return user_list;
	}
	
	
	/**
	 * 采购单据获取获取点数下拉人员信息
	 * @return
	 */
	public List<UserInfor> getProcureUses() {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		criteria.add(Restrictions.or(Restrictions.eq("roleType", ChainRoleType.HEAD_ACCOUNTING),Restrictions.eq("roleType", ChainRoleType.HEAD_SALE)));
		criteria.add(Restrictions.eq("resign", UserInfor.NORMAL_ACCOUNT));
		criteria.addOrder(Order.asc("pinyin"));
		
		List<UserInfor> user_list = this.getByCritera(criteria, true);
		
		return user_list;
	}
	
	
	public void addRoleFunctions(List<RoleFunctionality> roleFunctionalities) {
		this.getHibernateTemplate().setCacheQueries(true);
		for (int i =0; i < roleFunctionalities.size(); i++){
			RoleFunctionality functionality = roleFunctionalities.get(i);
			this.getHibernateTemplate().save(functionality);
		}
	}
	public UserInfor getUserByUserName(String userName) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		criteria.add(Restrictions.eq("user_name", userName));
		
		List<UserInfor> user_list = this.getByCritera(criteria, true);
		if (user_list == null || user_list.size()>1)
			return null;
		else 
			return user_list.get(0);
	}
	
	/**
	 * 获取会计部门一名人员
	 * @return
	 */
	public UserInfor getFinanceBillAccounting() {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		criteria.add(Restrictions.eq("department", UserInfor.ACCOUNTANT_CODE));
		criteria.add(Restrictions.eq("resign", UserInfor.NORMAL_ACCOUNT));
		
		List<UserInfor> user_list = this.getByCritera(criteria, true);
		if (user_list == null || user_list.size() == 0)
			return null;
		else 
			return user_list.get(0);
	}

	/**
	 * 获取会计部门人员
	 * @return
	 */
	public List<UserInfor> selectAccountings() {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		criteria.add(Restrictions.eq("department", UserInfor.ACCOUNTANT_CODE));
		criteria.add(Restrictions.eq("resign", UserInfor.NORMAL_ACCOUNT));
		
		List<UserInfor> user_list = this.getByCritera(criteria, true);

		return user_list;
	}
	
	
	/**
	 * 根据条件获取总部人员信息
	 * @param userInfor
	 * @return
	 */
	public List<UserInfor> getUsers(UserInfor userInfor) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		
		if (StringUtils.isNotBlank(userInfor.getDepartment()) && Integer.valueOf(userInfor.getDepartment()) != Common_util.ALL_RECORD_NEW) {
			criteria.add(Restrictions.eq("department", userInfor.getDepartment()));
		}
		if (userInfor.getRoleType() != Common_util.ALL_RECORD) {
			criteria.add(Restrictions.eq("roleType", userInfor.getRoleType()));
		}
		criteria.add(Restrictions.eq("resign", userInfor.getResign()));
		criteria.addOrder(Order.asc("user_id"));
		
		List<UserInfor> user_list = this.getByCritera(criteria, true);
		
		return user_list;
	}


}
